package com.example.singing.view;

import com.example.singing.manager.CompetitionManager;
import com.example.singing.manager.ScoreManager;
import com.example.singing.manager.TeamManager;
import com.example.singing.model.Competition;
import com.example.singing.model.Score;
import com.example.singing.model.Team;
import com.example.singing.util.AlertUtil;
import com.example.singing.util.SmartAnalyzer;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * 智能分析视图
 * 提供算法比较、AI问答和比赛分析等高级功能
 */
public class SmartAnalysisView {
    private VBox view;
    private CompetitionManager competitionManager;
    private TeamManager teamManager;
    private ScoreManager scoreManager;
    private TabPane tabPane;

    public SmartAnalysisView() {
        this.competitionManager = new CompetitionManager();
        this.teamManager = new TeamManager();
        this.scoreManager = new ScoreManager();
        createView();
    }

    /**
     * 创建智能分析界面
     */
    private void createView() {
        VBox mainContainer = new VBox(20);
        mainContainer.setPadding(new Insets(20));
        mainContainer.setStyle("-fx-background-color: #f5f5f5;");

        // 标题
        Label title = new Label("智能分析中心");
        title.setFont(Font.font("Arial", FontWeight.BOLD, 28));
        title.setStyle("-fx-text-fill: #2c3e50;");

        // 创建标签页
        tabPane = new TabPane();
        tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);

        // 添加各个功能标签页
        tabPane.getTabs().addAll(
                createAlgorithmTab(),
                createAiChatTab(),
                createCompetitionAnalysisTab()
        );

        // 设置标签页样式
        tabPane.setStyle(
                "-fx-background-color: white;"
        );

        mainContainer.getChildren().addAll(title, tabPane);
        
        // 添加滚动条功能
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(mainContainer);
        scrollPane.setFitToWidth(true); // 宽度自适应
        scrollPane.setFitToHeight(false); // 高度不自适应，允许垂直滚动
        scrollPane.setStyle("-fx-background: #f5f5f5; -fx-background-color: transparent;");
        
        this.view = new VBox(scrollPane);
        this.view.setStyle("-fx-background-color: #f5f5f5;");
    }

    /**
     * 创建算法比较标签页
     */
    private Tab createAlgorithmTab() {
        Tab tab = new Tab("评分算法比较");
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));

        // 算法说明
        Label description = new Label("比较传统评分算法与智能评分算法的差异，提高评分准确性");
        description.setStyle("-fx-font-size: 14px; -fx-text-fill: #666;");

        // 输入区域
        VBox inputArea = new VBox(15);
        inputArea.setStyle("-fx-background-color: #f9f9f9; -fx-background-radius: 10; -fx-padding: 20;");

        Label inputTitle = new Label("评委评分输入");
        inputTitle.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");

        GridPane inputGrid = new GridPane();
        inputGrid.setHgap(15);
        inputGrid.setVgap(10);

        // 创建5个评委评分输入框
        Slider[] judgeSliders = new Slider[5];
        Label[] scoreLabels = new Label[5];

        for (int i = 0; i < 5; i++) {
            Label judgeLabel = new Label("评委 " + (i + 1) + ":");
            judgeLabel.setStyle("-fx-font-weight: bold;");

            Slider slider = new Slider(0, 10, 8.5);
            slider.setShowTickMarks(true);
            slider.setShowTickLabels(true);
            slider.setMajorTickUnit(2);
            slider.setMinorTickCount(1);
            slider.setBlockIncrement(0.1);
            slider.setPrefWidth(300);

            Label scoreLabel = new Label(String.format("%.1f", slider.getValue()));
            scoreLabel.setPrefWidth(50);
            scoreLabel.setStyle("-fx-font-weight: bold;");

            // 更新分数显示
            slider.valueProperty().addListener((obs, oldVal, newVal) -> {
                scoreLabel.setText(String.format("%.1f", newVal));
            });

            inputGrid.add(judgeLabel, 0, i);
            inputGrid.add(slider, 1, i);
            inputGrid.add(scoreLabel, 2, i);
            
            judgeSliders[i] = slider;
            scoreLabels[i] = scoreLabel;
        }

        // 比较按钮
        Button compareBtn = new Button("比较算法");
        compareBtn.setStyle("-fx-background-color: #673ab7; -fx-text-fill: white; -fx-font-weight: bold;");
        compareBtn.setPrefWidth(150);

        // 结果显示区域
        VBox resultArea = new VBox(15);
        resultArea.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 5, 0, 0, 2);");

        Label resultTitle = new Label("算法比较结果");
        resultTitle.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");

        HBox resultsBox = new HBox(30);
        resultsBox.setPadding(new Insets(10));

        // 传统算法结果
        VBox traditionalBox = new VBox(10);
        traditionalBox.setStyle("-fx-background-color: #e3f2fd; -fx-background-radius: 10; -fx-padding: 20; -fx-min-width: 200;");
        Label traditionalTitle = new Label("传统算法");
        traditionalTitle.setStyle("-fx-font-weight: bold; -fx-text-fill: #1565c0;");
        Label traditionalResult = new Label("- 分");
        traditionalResult.setStyle("-fx-font-size: 24px; -fx-font-weight: bold; -fx-text-fill: #1565c0;");
        Label traditionalDesc = new Label("去掉最高分和最低分，取平均");
        traditionalDesc.setStyle("-fx-font-size: 12px; -fx-text-fill: #666; -fx-wrap-text: true;");
        traditionalBox.getChildren().addAll(traditionalTitle, traditionalResult, traditionalDesc);

        // 智能算法结果
        VBox smartBox = new VBox(10);
        smartBox.setStyle("-fx-background-color: #e8f5e9; -fx-background-radius: 10; -fx-padding: 20; -fx-min-width: 200;");
        Label smartTitle = new Label("智能算法");
        smartTitle.setStyle("-fx-font-weight: bold; -fx-text-fill: #2e7d32;");
        Label smartResult = new Label("- 分");
        smartResult.setStyle("-fx-font-size: 24px; -fx-font-weight: bold; -fx-text-fill: #2e7d32;");
        Label smartDesc = new Label("离群值检测 + 加权平均分 + 智能校准");
        smartDesc.setStyle("-fx-font-size: 12px; -fx-text-fill: #666; -fx-wrap-text: true;");
        smartBox.getChildren().addAll(smartTitle, smartResult, smartDesc);

        resultsBox.getChildren().addAll(traditionalBox, smartBox);

        // 添加AI分析结果
        TextArea analysisText = new TextArea();
        analysisText.setEditable(false);
        analysisText.setPrefHeight(100);
        analysisText.setPromptText("AI分析结果将显示在这里...");
        analysisText.setStyle("-fx-font-size: 14px; -fx-background-color: #f5f5f5;");

        resultArea.getChildren().addAll(resultTitle, resultsBox, analysisText);

        // 设置比较按钮事件
        compareBtn.setOnAction(e -> {
            // 收集评分
            double[] scores = new double[5];
            List<Double> scoreList = new ArrayList<>();
            
            for (int i = 0; i < 5; i++) {
                scores[i] = judgeSliders[i].getValue();
                scoreList.add(scores[i]);
            }

            // 计算传统算法得分（去掉最高分和最低分，取平均）
            Arrays.sort(scores);
            double sum = 0;
            for (int i = 1; i < 4; i++) {
                sum += scores[i];
            }
            double traditionalScore = sum / 3;

            // 计算智能算法得分
            double smartScore = SmartAnalyzer.calculateAdvancedScore(scoreList);

            // 显示结果
            traditionalResult.setText(String.format("%.2f 分", traditionalScore));
            smartResult.setText(String.format("%.2f 分", smartScore));

            // 生成AI分析
            StringBuilder analysis = new StringBuilder();
            analysis.append("=== AI评分分析 ===\n\n");
            
            if (Math.abs(smartScore - traditionalScore) > 0.5) {
                analysis.append("1. 两种算法结果差异显著 (>")
                        .append(String.format("%.2f", Math.abs(smartScore - traditionalScore)))
                        .append("分)\n");
            } else {
                analysis.append("1. 两种算法结果较为接近 (差异 < 0.5分)\n");
            }
            
            // 分析分数分布
            double maxScore = scoreList.stream().mapToDouble(Double::doubleValue).max().orElse(0);
            double minScore = scoreList.stream().mapToDouble(Double::doubleValue).min().orElse(0);
            double avgScore = scoreList.stream().mapToDouble(Double::doubleValue).average().orElse(0);
            
            analysis.append("2. 原始分数统计：\n")
                    .append("   - 最高分: ").append(String.format("%.2f", maxScore)).append("分\n")
                    .append("   - 最低分: ").append(String.format("%.2f", minScore)).append("分\n")
                    .append("   - 平均分: ").append(String.format("%.2f", avgScore)).append("分\n")
                    .append("   - 分差: ").append(String.format("%.2f", maxScore - minScore)).append("分\n\n");
            
            if (maxScore - minScore > 1.5) {
                analysis.append("3. 评委评分差异较大，建议使用智能算法获得更准确的结果\n");
                analysis.append("4. 建议对评委进行统一培训，减少主观评分差异");
            } else {
                analysis.append("3. 评委评分较为一致，两种算法结果都可参考\n");
                analysis.append("4. 推荐使用智能算法进一步提高评分准确性");
            }
            
            analysisText.setText(analysis.toString());
        });

        HBox buttonBox = new HBox();
        buttonBox.setPadding(new Insets(10));
        buttonBox.setAlignment(javafx.geometry.Pos.CENTER);
        buttonBox.getChildren().add(compareBtn);

        inputArea.getChildren().addAll(inputTitle, inputGrid, buttonBox);

        content.getChildren().addAll(description, inputArea, resultArea);
        tab.setContent(content);
        return tab;
    }

    /**
     * 创建AI问答标签页
     */
    private Tab createAiChatTab() {
        Tab tab = new Tab("AI智能问答");
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));

        // 说明文字
        Label description = new Label("智能问答助手可以回答关于评分系统、比赛分析等相关问题");
        description.setStyle("-fx-font-size: 14px; -fx-text-fill: #666;");

        // 聊天界面
        VBox chatArea = new VBox(10);
        chatArea.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20;");

        // 历史消息显示区域
        TextArea chatHistory = new TextArea();
        chatHistory.setEditable(false);
        chatHistory.setPrefHeight(300);
        chatHistory.setStyle("-fx-font-size: 14px; -fx-background-color: #f5f5f5;");
        chatHistory.setText("AI助手: 您好！我是智能问答助手，请问有什么可以帮助您的？\n\n");

        // 输入区域
        HBox inputBox = new HBox(10);

        TextField questionField = new TextField();
        questionField.setPromptText("请输入您的问题...");
        questionField.setPrefHeight(40);
        questionField.setStyle("-fx-font-size: 14px;");

        Button askBtn = new Button("提问");
        askBtn.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white; -fx-font-weight: bold;");
        askBtn.setPrefHeight(40);
        askBtn.setPrefWidth(80);

        // 提问按钮事件
        askBtn.setOnAction(e -> {
            String question = questionField.getText().trim();
            if (question.isEmpty()) {
                AlertUtil.showWarningAlert("提示", "请输入您的问题");
                return;
            }

            // 添加用户问题到聊天历史
            chatHistory.appendText("您: " + question + "\n\n");

            // 显示AI正在思考
            chatHistory.appendText("AI助手: 正在思考...\n");
            chatHistory.setScrollTop(Double.MAX_VALUE); // 滚动到底部

            // 模拟AI思考延迟
            new Thread(() -> {
                try {
                    Thread.sleep(1000); // 模拟思考时间
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }

                // 调用AI问答功能
                String answer = SmartAnalyzer.answerQuestion(question);

                // 在JavaFX应用线程中更新UI
                javafx.application.Platform.runLater(() -> {
                    // 替换正在思考的文本
                    String currentText = chatHistory.getText();
                    int lastIndex = currentText.lastIndexOf("AI助手: 正在思考...\n");
                    if (lastIndex >= 0) {
                        currentText = currentText.substring(0, lastIndex);
                    }
                    chatHistory.setText(currentText);
                    
                    // 添加AI回答
                    chatHistory.appendText("AI助手: " + answer + "\n\n");
                    chatHistory.setScrollTop(Double.MAX_VALUE); // 滚动到底部
                });
            }).start();

            // 清空输入框
            questionField.clear();
        });

        // 设置输入框回车提问
        questionField.setOnAction(e -> askBtn.fire());

        HBox.setHgrow(questionField, Priority.ALWAYS);
        inputBox.getChildren().addAll(questionField, askBtn);

        chatArea.getChildren().addAll(chatHistory, inputBox);

        // 常见问题提示
        VBox faqBox = new VBox(10);
        faqBox.setStyle("-fx-background-color: #f9f9f9; -fx-background-radius: 10; -fx-padding: 20;");

        Label faqTitle = new Label("常见问题");
        faqTitle.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");

        VBox faqItems = new VBox(5);
        String[] faqs = {
            "如何提高评分准确性",
            "如何分析比赛结果",
            "评分标准",
            "如何减少评委差异"
        };

        for (String faq : faqs) {
            Hyperlink link = new Hyperlink(faq);
            link.setStyle("-fx-text-fill: #2196f3; -fx-font-size: 14px;");
            link.setOnAction(e -> questionField.setText(faq));
            faqItems.getChildren().add(link);
        }

        faqBox.getChildren().addAll(faqTitle, faqItems);

        content.getChildren().addAll(description, chatArea, faqBox);
        tab.setContent(content);
        return tab;
    }

    /**
     * 创建比赛分析标签页
     */
    private Tab createCompetitionAnalysisTab() {
        Tab tab = new Tab("比赛智能分析");
        VBox content = new VBox(20);
        content.setPadding(new Insets(20));

        // 说明文字
        Label description = new Label("生成比赛详细分析报告，提供AI建议和数据洞察");
        description.setStyle("-fx-font-size: 14px; -fx-text-fill: #666;");

        // 选择比赛区域
        HBox selectionBox = new HBox(20);
        selectionBox.setStyle("-fx-background-color: #f9f9f9; -fx-background-radius: 10; -fx-padding: 20;");

        Label selectLabel = new Label("选择比赛:");
        selectLabel.setStyle("-fx-font-weight: bold;");

        ComboBox<Competition> competitionCombo = new ComboBox<>();
        competitionCombo.setItems(javafx.collections.FXCollections.observableArrayList(competitionManager.getAllCompetitions()));
        competitionCombo.setPromptText("请选择要分析的比赛");
        competitionCombo.setPrefWidth(300);

        Button generateBtn = new Button("生成分析报告");
        generateBtn.setStyle("-fx-background-color: #4caf50; -fx-text-fill: white; -fx-font-weight: bold;");

        selectionBox.getChildren().addAll(selectLabel, competitionCombo, generateBtn);

        // 报告显示区域
        TextArea reportArea = new TextArea();
        reportArea.setEditable(false);
        reportArea.setPrefHeight(400);
        reportArea.setStyle("-fx-font-size: 14px; -fx-background-color: white;");
        reportArea.setPromptText("分析报告将显示在这里...");

        // 生成报告按钮事件
        generateBtn.setOnAction(e -> {
            Competition selectedCompetition = competitionCombo.getValue();
            if (selectedCompetition == null) {
                AlertUtil.showWarningAlert("提示", "请先选择要分析的比赛");
                return;
            }

            // 获取该比赛的所有评分和队伍
            List<Score> competitionScores = scoreManager.getScoresByCompetitionId(selectedCompetition.getId());
            List<Team> competitionTeams = teamManager.getAllTeams().stream()
                    .filter(team -> team.getCompetitionId().equals(selectedCompetition.getId()))
                    .collect(java.util.stream.Collectors.toList());

            if (competitionScores.isEmpty()) {
                AlertUtil.showWarningAlert("提示", "该比赛暂无评分数据，无法生成分析报告");
                return;
            }

            // 生成分析报告
            String report = SmartAnalyzer.generateCompetitionReport(competitionScores, competitionTeams);
            reportArea.setText(report);

            // 显示生成成功提示
            AlertUtil.showInfoAlert("成功", "比赛分析报告已生成");
        });

        content.getChildren().addAll(description, selectionBox, reportArea);
        tab.setContent(content);
        return tab;
    }

    /**
     * 获取界面视图
     */
    public VBox getView() {
        return view;
    }
}